package at.stefanirndorfer.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

import at.stefanirndorfer.jframe.SuchApplikationFrame;

public class Lucene {

	private static final String INDEX_PATH = "indexDir";

	StandardAnalyzer analyzer;
	Directory index;
	TextFileIndexer indexer;
	SuchApplikationFrame frame;

	public Lucene(SuchApplikationFrame frame) {
		this.frame = frame;

		try {
			inizialize();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void inizialize() throws IOException, ParseException {

		analyzer = new StandardAnalyzer(Version.LUCENE_46);

		// 1. create the index
		index = new RAMDirectory();

		String indexLocation = INDEX_PATH;
		TextFileIndexer indexer = null;

		indexer = new TextFileIndexer(indexLocation, analyzer);

		// debug:
		indexer.indexFileOrDirectory("documents");

		// ===================================================
		// after adding, we always have to call the
		// closeIndex, otherwise the index is not created
		// ===================================================
		indexer.closeIndex();

		// =========================================================
		// Now search
		// =========================================================
		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
				indexLocation)));
		IndexSearcher searcher = new IndexSearcher(reader);
		TopScoreDocCollector collector = TopScoreDocCollector.create(5, true);

		String s = "Letters";
		Query q = new QueryParser(Version.LUCENE_46, "contents", analyzer)
				.parse(s);
		searcher.search(q, collector);
		ScoreDoc[] hits = collector.topDocs().scoreDocs;

		// 4. display results
		System.out.println("Found " + hits.length + " hits.");
		for (int i = 0; i < hits.length; ++i) {
			int docId = hits[i].doc;
			Document d = searcher.doc(docId);
			System.out.println((i + 1) + ". " + d.get("path") + " score="
					+ hits[i].score);
			//frame.

		}
	}
}
